import React, { useEffect, useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { RcFile } from 'antd/es/upload/interface';
import dayjs from 'dayjs'

import { cos } from '@/utils/cos';

interface Iprops {
	getImgUrl: (url: string) => void
	src?: string
}

const MyUpload: React.FC<Iprops> = (props) => {
	const [loading, setLoading] = useState(false);
	const [imageUrl, setImageUrl] = useState<string>();
	const { getImgUrl, src } = props

	useEffect(() => {
		if (src) {
			setImageUrl(src)
		}
	}, [src])

	const beforeUpload = (file: RcFile) => {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		if (!isJpgOrPng) {
			message.error('You can only upload JPG/PNG file!');
		}
		setLoading(true)
		setImageUrl('')
		cos.uploadFile({
			Body: file,
			Bucket: 'graduation-1314402370',
			Region: 'ap-chongqing',
			Key: `picture/${dayjs().format()}`,
		}).then(data => {
			setImageUrl('http://' + data.Location)
			getImgUrl('http://' + data.Location)
			setLoading(false)
		}, err => {
			console.log(err);
			setLoading(false)
		})
	};

	const uploadButton = (
		<div>
			{loading ? <LoadingOutlined /> : <PlusOutlined />}
			<div style={{ marginTop: 8 }}>Upload</div>
		</div>
	);
	return (
		<>
			<Upload
				name="avatar"
				listType="picture-card"
				className="avatar-uploader"
				showUploadList={false}
				beforeUpload={beforeUpload}
			>
				{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
			</Upload>
		</>
	);
};

export default MyUpload;